import request from '@/utils/request'
import { useUserStore } from '@/store/user'

/**
 * 导入导出 API
 */

// 导入学生信息
export const importStudent = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/import-export/import/student',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 导入成绩数据
export const importScore = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/import-export/import/score',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取导入历史
export const getImportHistory = () => {
  return request({
    url: '/import-export/import/history',
    method: 'get'
  })
}

// 获取带token的URL
const getAuthUrl = (url: string) => {
  const userStore = useUserStore()
  const token = userStore.token
  const separator = url.includes('?') ? '&' : '?'
  return `${url}${separator}satoken=${encodeURIComponent(token)}`
}

// 下载模板
export const downloadTemplate = (type: string) => {
  const url = getAuthUrl(`/api/import-export/template/download?type=${type}`)
  window.open(url)
}

// 导出学生信息
export const exportStudent = () => {
  const url = getAuthUrl('/api/import-export/export/student')
  window.open(url)
}

// 导出成绩数据
export const exportScore = (semester: string) => {
  const url = getAuthUrl(`/api/import-export/export/score?semester=${semester}`)
  window.open(url)
}

// 导出学籍汇总表
export const exportSummary = () => {
  const url = getAuthUrl('/api/import-export/export/summary')
  window.open(url)
}

// 导出档案记录
export const exportRecord = () => {
  const url = getAuthUrl('/api/import-export/export/record')
  window.open(url)
}

// 打包毕业档案
export const exportPackage = (studentNo: string) => {
  const url = getAuthUrl(`/api/import-export/export/package?studentNo=${studentNo}`)
  window.open(url)
}

